import React from 'react';
import { withRouter } from 'umi';
import { Form, Empty, Input } from 'antd';

import { controlFields as formItems } from '@/pages/WorkFlow/components/FormControls/formConfig/custom/dimissionApply';
// import { TitleControl } from '@/pages/Recruitment/components';
import { CollapseHeader as TitleControl } from '@/pages/OnboardAndLeave/LeaveManagement/Handover/components';
import { getSummary } from '@/pages/WorkFlow/Flow/utils';
import { useBeforeSubmit } from '@/pages/WorkFlow/hooks';
import { useRequest, defaultFormatResult, useEmployeeData } from '@/hooks';
import { renderOptionValue, getLeafId, getPath } from '@/utils/utils';

import { getDimissionDetail } from '@/pages/OnboardAndLeave/LeaveManagement/service';

import { Info, History, Attendance, Probation, Profile, Append, Talk, ProfileProxy } from './containers';
import { TYPE_LIST } from './constants';

const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 }
};

// 小朋友，你是不是有很多问号
// 转化接口的格式
const generateSceneData = (originScene = [], severType) => {
    const severTypeScene = originScene[severType] ?? {};
    const { applySceneId: originSceneId = [] } = severTypeScene;
    return originSceneId.map(item => {
        const applySceneId = getLeafId(item);
        const rulesId = severTypeScene?.ruleCorrelationIds?.[applySceneId] ?? [];
        const files = severTypeScene?.files?.[applySceneId] ?? [];
        const scenesFileDisplay = severTypeScene?.scenesFileDisplay?.[applySceneId] ?? [];
        return {
            applySceneId,
            files,
            scenesFileDisplay,
            ruleCorrelationIds: rulesId.map(it => getLeafId(it))
        };
    });
};

const reverseGenerateSceneData = (originScene = [], severType, detailScene = []) => {
    if (!severType) return [];
    const scenes = [];
    const applySceneId = originScene.map(item => getPath([severType, item.applySceneId]));
    const ruleCorrelationIds = originScene.reduce((prev, cur) => {
        const nextPrev = prev;
        const prefix = getPath([severType, cur.applySceneId]);
        const rulesId = cur.ruleCorrelationIds ?? [];
        nextPrev[cur.applySceneId] = rulesId.map(item => getPath([prefix, item])) ?? [];
        return nextPrev;
    }, []);
    const files = originScene.reduce((prev, cur) => {
        const nextPrev = prev;
        const detailTarget = detailScene.find(item => item.applySceneId === cur.applySceneId);
        nextPrev[cur.applySceneId] = detailTarget?.files ?? [];
        return nextPrev;
    }, []);

    scenes[severType] = {
        applySceneId,
        ruleCorrelationIds,
        scenesFileDisplay: files
    };
    return scenes;
};

// 离职申请
const DimissionApply = ({
    form,
    formValueMap: originFormValueMap = {},
    location,
    dataSource = { children: [] },
    isProxy = false,
    processInstanceId: instanceId,
    tag
}) => {
    const { query = {} } = location;

    const queryEmployeeCode = isProxy ? query.leaverEmployeeCode : query.employeeCode;

    const employeeCode =
        form.getFieldValue('leaverEmployeeCode') ?? originFormValueMap.leaverEmployeeCode ?? queryEmployeeCode;
    const processInstanceId = query.processInstanceId ?? instanceId; // hmm...

    const { children = [] } = dataSource;
    const { data: detailData = {} } = useRequest(() => getDimissionDetail(processInstanceId), {
        ready: !!processInstanceId,
        ...defaultFormatResult
    });

    // 这里mixin当前formValues? 算了...难以处理
    const formValueMap = {
        ...originFormValueMap,
        filesDisplay: detailData.files,
        scenes: reverseGenerateSceneData(originFormValueMap.scenes, originFormValueMap.severType, detailData.scenes)
    };

    // 设计：复杂且无意义的表单项可见控制
    // 服务支持：流程基础服务提供的可读性极差的控制方式

    // 流程设计中“表单权限”使用会引起children数据的变化，以此来控制表单项的可见与可编辑，需要留意的点：
    // A.流程表单权限的字段需要提交值才可生效
    // B.发起时使用只读会达到隐藏的作用
    // C.使用隐藏会直接丢掉对应表单项
    // D.只能控制流程节点中设置的处理人，其他用户查看时都默认为不可编辑（大概？）
    const checkVisible = React.useCallback(
        (fieldName, hasEmployeeCode = employeeCode) =>
            hasEmployeeCode && children.some(item => item.formId === fieldName && item.options && !item.options.hidden),
        [children, employeeCode]
    );
    const checkEditable = React.useCallback(
        fieldName => children.some(item => item.formId === fieldName && item.options && !item.options.disabled),
        [children]
    );

    // 大为震撼
    const showProfileForm =
        !formValueMap.leaverEmployeeCode && !query.leaverEmployeeCode && isProxy && checkEditable('__profile');
    const showProfileCard = !showProfileForm;

    const { data: employeeData = {} } = useEmployeeData(employeeCode, { useLastApprove: false });
    const { employeeName, serviceStatus } = employeeData;

    // 试用员工
    const isProbation = serviceStatus === 4;

    const commonProps = {
        form,
        employeeCode,
        employeeData,
        formValueMap
    };

    const talkProps = {
        processInstanceId,
        employeeCode,
        employeeName
    };

    const dimissionType = form.getFieldValue('dimissionType');
    React.useEffect(() => {
        const summary = getSummary({
            离职人员: employeeName,
            离职类型: renderOptionValue(TYPE_LIST, dimissionType)
        });
        form.setFieldsValue({ applicationAbstract: summary });
    }, [employeeName, dimissionType, TYPE_LIST]);

    const { setHandler } = useBeforeSubmit(tag);

    // 对提交的数据做处理
    const beforeSubmit = (values = {}) => {
        const { scenes, ...rest } = values;

        return {
            ...rest, // 可否增量更新？
            scenes: generateSceneData(scenes, values.severType) // 格式化
        };
    };
    setHandler(beforeSubmit);

    return (
        <>
            {showProfileCard && (
                <>
                    <Profile initialData={employeeData} style={{ marginBottom: 20 }} />
                    <Form.Item style={{ display: 'none' }}>
                        {form.getFieldDecorator('leaverEmployeeCode', { initialValue: employeeCode })(<Input />)}
                    </Form.Item>
                </>
            )}
            <Form {...formItemLayout}>
                {showProfileForm && (
                    <TitleControl title="个人信息" headerStyle={{ borderTop: 'none' }}>
                        <ProfileProxy form={form} employeeCode={employeeCode} initialData={employeeData} />
                    </TitleControl>
                )}
                {checkVisible('__info', true) && (
                    <TitleControl title="离职信息">
                        <Info {...commonProps} isEdit={checkEditable('__info')} isProxy={isProxy} />
                    </TitleControl>
                )}
                {checkVisible('__talk') && (
                    <TitleControl title="离职面谈">
                        <Talk {...talkProps} isEdit={checkEditable('__talk')} />
                        <Form.Item style={{ display: 'none' }}>
                            {form.getFieldDecorator('dimissionInterviewFlag')(<Input />)}
                        </Form.Item>
                    </TitleControl>
                )}
                {checkVisible('__append') && (
                    <TitleControl title="补充信息">
                        <Append {...commonProps} isEdit={checkEditable('__append')} applyTime={detailData.applyTime} />
                    </TitleControl>
                )}
                {checkVisible('__history') && (
                    <TitleControl title="微微历程" defaultExpand={false}>
                        <History employeeCode={employeeCode} />
                    </TitleControl>
                )}
                {checkVisible('__work') && (
                    <TitleControl title="工作任务" defaultExpand={false}>
                        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                    </TitleControl>
                )}
                {checkVisible('__attendance') && (
                    <TitleControl title="考勤情况" defaultExpand={false}>
                        <Attendance employeeCode={employeeCode} />
                    </TitleControl>
                )}

                {isProbation && checkVisible('__probation') && (
                    <TitleControl title="试用期考评" defaultExpand={false}>
                        <Probation employeeCode={employeeCode} />
                    </TitleControl>
                )}

                <div style={{ display: 'none' }}>
                    {/* 只有表单存在值，权限配置项才能生效... */}
                    {formItems.map(item => (
                        <Form.Item key={item.key}>
                            {form.getFieldDecorator(item.key, { initialValue: 1 })(<Input />)}
                        </Form.Item>
                    ))}
                    <Form.Item>{form.getFieldDecorator('applicationAbstract')(<Input />)}</Form.Item>
                    <Form.Item>{form.getFieldDecorator('workFlowTag', { initialValue: tag })(<Input />)}</Form.Item>
                </div>
            </Form>
        </>
    );
};

export default withRouter(DimissionApply);
